package com.example.oss.advice;

import com.alibaba.fastjson.JSON;
import com.example.oss.entity.Result;
import com.example.oss.entity.ResultEnum;
import com.example.oss.exception.VersionException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@ControllerAdvice(annotations = Controller.class)
@Slf4j
public class ExceptionAdvice {

    @ExceptionHandler(Exception.class)
    public void handlerException(HttpServletRequest request, HttpServletResponse response, Exception e) throws IOException {

        log.error("服务器发生异常：{}", e.getMessage());
        for (StackTraceElement stackTraceElement : e.getStackTrace()) {
            log.error(stackTraceElement.toString());
        }

        String xRequestedWith = request.getHeader("x-requested-with");
        if ("XMLHttpRequest".equals(xRequestedWith)) {
            response.setContentType("application/json");
            response.setCharacterEncoding("UTF-8");
            PrintWriter writer = response.getWriter();
            writer.write(JSON.toJSONString(Result.failure(ResultEnum.ERROR)));
            writer.flush();
            writer.close();
        } else {
            response.sendRedirect(request.getContextPath() + "/500");
        }
    }


    //捕捉valid参数校验异常
    @ExceptionHandler(BindException.class)
    @ResponseBody
    public Result paramCheck(BindException e) {
        String defaultMessage = e.getBindingResult().getFieldError().getDefaultMessage();
        return Result.failure(defaultMessage);
    }


    //捕捉减库存失败异常
    @ExceptionHandler(VersionException.class)
    @ResponseBody
    public Result versionConcurrent(VersionException e) {
        log.error(e.getMessage());
        e.printStackTrace();
        return Result.failure("数据正在处理，请稍后重试！");
    }


}
